//------------------------------------------------------------------------------
#include <QtGui>
#include <QMessageBox>
#include <QDate>
#include <QHash>
#include <QSqlRecord>
#include "CFindFrm.h"
#include "CArticleFrm.h"
#include "CEntreesSortiesDeStockFrm.h"
#include "CMyTableWidgetItem.h"
#include "CComboResultFrm.h"
#include "version.h"
#include "CMySQL.h"
#include "CHelp.h"
//------------------------------------------------------------------------------
CArticleFrm::CArticleFrm(QString name, QString lastCode, QWidget *parent) : CMyMainWindow(name, parent) {	
	setActionCur(CGlobal::acConstruct);
	
	setupUi(this);
;
	setStatusBar(NULL);
	
	masterTable="article";
	primaryKey="code";
	
	tabWidget->removeTab(0);
	
	createGrilleVentes();
	createGrilleMvtStock();
	
	loadSchema();
	
	if(CMySQL::getInstance()->getNbEnregistrement(masterTable) == 0) {
		setActionCur(CGlobal::acTableVide);
	}else {
		if(!chargeDonnees(lastCode, CGlobal::seNone)) chargeDonnees("", CGlobal::sePremier);
	}
}
//------------------------------------------------------------------------------
void CArticleFrm::setActionCur(CGlobal::EAction action) {
	actionCur=action;
	
	switch(actionCur) {
		case CGlobal::acNone:
			actPremiereFiche->setEnabled(true);
			actFichePrecedente->setEnabled(true);
			actFicheSuivante->setEnabled(true);
			actDerniereFiche->setEnabled(true);
			
			actAjouter->setEnabled(true);
			actSupprimer->setEnabled(true);
			
			actValider->setEnabled(false);
			actAnnuler->setEnabled(false);
			
			actRechercheUneFiche->setEnabled(true);
			
			actEntreesSorties->setEnabled(gereStock->checkState() == Qt::Checked);
			
			enableChamps(true);
			code->setEnabled(false);
			tabWidget->setEnabled(true);
			break;
		case CGlobal::acTableVide:
			actPremiereFiche->setEnabled(false);
			actFichePrecedente->setEnabled(false);
			actFicheSuivante->setEnabled(false);
			actDerniereFiche->setEnabled(false);
			
			actAjouter->setEnabled(true);
			actSupprimer->setEnabled(false);
			
			actValider->setEnabled(false);
			actAnnuler->setEnabled(false);
			
			actRechercheUneFiche->setEnabled(false);
			actEntreesSorties->setEnabled(false);
			
			clearChamps();
			enableChamps(false);
			creation->setValue("");
			stock->setValue("0.00");
			prixUnitaireHT->setValue("0.00");
			tabWidget->setEnabled(false);
			break;
		case CGlobal::acAjout:
			clearChamps();
			initChamps();
			enableChamps(true);
			code->setFocus();
		case CGlobal::acModif:
			actPremiereFiche->setEnabled(false);
			actFichePrecedente->setEnabled(false);
			actFicheSuivante->setEnabled(false);
			actDerniereFiche->setEnabled(false);
			
			actAjouter->setEnabled(false);
			actSupprimer->setEnabled(false);
			
			actValider->setEnabled(true);
			actAnnuler->setEnabled(true);
			
			actRechercheUneFiche->setEnabled(false);
			
			actEntreesSorties->setEnabled(false);
			tabWidget->setEnabled(false);
		default:
			break;
	}
}
//------------------------------------------------------------------------------
CGlobal::EAction CArticleFrm::getActionCur(void) {
	return actionCur;
}
//------------------------------------------------------------------------------
void CArticleFrm::closeEvent(QCloseEvent * event) {
	if(getActionCur() != CGlobal::acNone && getActionCur() != CGlobal::acTableVide) {
		QMessageBox msgBox(	QMessageBox::Warning, tr("Attention"), 
							tr("Veuillez annuler ou valider avant de sortir"), QMessageBox::Ok);
		msgBox.exec();	
		
		event->ignore();
	}else {
		emit quit(objectName(), curCode);
		event->accept();
	}
}
//------------------------------------------------------------------------------
void CArticleFrm::resizeEvent(QResizeEvent * event) {
	QSize wndSize=event->size();
	int height=centralWidget()->size().height()-140;
	
	if(height > 0) {
		tabWidget->setFixedSize(wndSize.width()-20, height);
		tabWidget->move(10, 130);
	}
	
	QMainWindow::resizeEvent(event);
}
//------------------------------------------------------------------------------
void CArticleFrm::createGrilleVentes(void) {
	QList<CColumnModel *> *columnModel=new QList<CColumnModel *>();
	QHash<QString, QString> filters;
	
	filters[tr("Année")]="YEAR(tf.creation)=%1";
	
	columnModel->append(new CColumnModelString(cnvCClient, "codeCLient", tr("Code client"), Qt::AlignLeft, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelString(cnvClient, "nom", tr("Client"), Qt::AlignLeft, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelInt(cnvNbL, "nbL", tr("Nombre de ligne"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelDouble(cnvQte, "squantité", tr("Quantité"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelDouble(cnvMnt, "montant", tr("Montant"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
		
	ventesWidget=new CGrilleWidget(columnModel, this, false, false, true);
	connect(ventesWidget, SIGNAL(filter(QString)), this, SLOT(filterVentes(QString)));
	ventesWidget->setFilters(filters);
	tabWidget->addTab(ventesWidget, tr("Ventes"));
	
	ventesWidget->setColumnWidth(cnvNbL, 150);
	ventesWidget->setColumnWidth(cnvClient, 400);
}
//------------------------------------------------------------------------------
void CArticleFrm::loadGrilleVentes(QString filter) {
	CGlobal::EAction oldAction=getActionCur();
	QString requete;
	QSqlQuery *query;
	
	setActionCur(CGlobal::acAfficheLigne);
	
	requete="SELECT codeClient, nom, count(bl) AS nbL, sum(quantite) AS sQuantite, ";
	requete+="SUM(prixUnitaireHT*quantite*IF(document=\"A\", -1, 1))";
	requete+="FROM teteFactures AS tf INNER JOIN ligneFactures ON facture=tf.code ";
	requete+="INNER JOIN client AS c ON codeClient=c.code ";
	requete+="WHERE article=\""+curCode+"\" ";
	if(filter != "") {
		requete+="AND "+filter;
	}
	requete+=" GROUP BY codeClient";
	
	if(CMySQL::getInstance()->execQuery(requete, &query)) {
		ventesWidget->loadGrille(query);
	}
	delete query;
	
	setActionCur(oldAction);
}
//------------------------------------------------------------------------------
void CArticleFrm::createGrilleMvtStock(void) {
	QList<CColumnModel *> *columnModel=new QList<CColumnModel *>();
	
	columnModel->append(new CColumnModelDate(cnmsDate, "dateMouvement", tr("Date"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelDouble(cnmsStockAv, "stockAvant", tr("Stock avant mvt."), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelDouble(cnmsMv, "mouvement", tr("mvt."), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelDouble(cmnsStockApres, "stockApres", tr("Stock après (?)"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelInt(cmnsBL, "bl", tr("BL"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelInt(cnmsLigneBL, "numeroLigneBl", tr("Ligne de BL"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
															
	mvtStockWidget=new CGrilleWidget(columnModel, this, false);
	tabWidget->addTab(mvtStockWidget, tr("Mouvements de stock"));
	
	mvtStockWidget->setColumnWidth(cnmsStockAv, 150);
	mvtStockWidget->setColumnWidth(cmnsStockApres, 150);
}
//------------------------------------------------------------------------------
void CArticleFrm::loadGrilleMvtStock(void) {
	CGlobal::EAction oldAction=getActionCur();
	QString requete;
	QSqlQuery *query;
	
	setActionCur(CGlobal::acAfficheLigne);
	
	requete="SELECT dateMouvement, stockAvant, mouvement, stockAvant+mouvement AS stockApres, bl, numeroLigneBl ";
	requete+="FROM mouvementStock ";
	requete+="WHERE article=\""+curCode+"\" ORDER BY idMouvement";
	
	if(CMySQL::getInstance()->execQuery(requete, &query)) {
		mvtStockWidget->loadGrille(query);
	}
	delete query;
	
	setActionCur(oldAction);
}
//------------------------------------------------------------------------------
void CArticleFrm::makeRequete(QString &requete, QString &alias) {
	requete="SELECT a.*, t.Nom AS tvaNom FROM "+masterTable+" AS a INNER JOIN tva AS t ON a.idTva=t.id";
}
//------------------------------------------------------------------------------
void CArticleFrm::showFormulaire(QSqlQuery *query, CGlobal::EAction& action) {
	QSqlRecord rec=query->record();
	
	curCode=rec.value("code").toString();
	code->setValue(curCode);
	nom->setValue(rec.value("nom"));
	famille->setValue(rec.value("famille"));
	prixUnitaireHT->setValue(rec.value("prixUnitaireHT"));
	creation->setValue(rec.value("creation"));
	unite->setValue(rec.value("unite"));
	gereStock->setValue(rec.value("gereStock"));
	
	stock->setValue(rec.value("stock"));
	
	idTva->setValue(rec.value("idTva"));
	tvaNom->setValue(rec.value("tvaNom"));
		
	ventesWidget->clearTable();
	ventesWidget->clearFilter();
	loadGrilleVentes(ventesWidget->getFilter());
	loadGrilleMvtStock();
}
//------------------------------------------------------------------------------
void CArticleFrm::on_actAjouter_triggered(void) {
	setActionCur(CGlobal::acAjout);
	
	ventesWidget->setRowCount(0);
	mvtStockWidget->setRowCount(0);
	
	prixUnitaireHT->setValue("0.00");
	creation->setValue(CMySQL::getInstance()->getCurrentDate());
}
//------------------------------------------------------------------------------
void CArticleFrm::on_actValider_triggered(void) {
	QString requete;
	QString condition;
	
	code->setText(code->text().toUpper());
	calculChamps(getActionCur());
	
	if(!validChamps()) return;
	if(!validLiaison()) return;
	
	switch(getActionCur()) {
		case CGlobal::acAjout:
			requete="INSERT INTO "+masterTable+" SET "+primaryKey+"=\""+code->getValue()+"\", ";
			requete+="creation=CURDATE(), createur=\""+CMySQL::getInstance()->getUser()+"\", ";
			condition="";
			break;
		case CGlobal::acModif:
			requete="UPDATE "+masterTable+" SET ";
			requete+="modification=CURDATE(), modificateur=\""+CMySQL::getInstance()->getUser()+"\", ";
			condition="WHERE "+primaryKey+"=\""+code->getValue()+"\"";
			break;
		default:
			return;
	}
	
	requete+="nom = \""+nom->getValue()+"\", famille = \""+famille->getValue()+"\", ";
	requete+="prixUnitaireHT="+QString::number(prixUnitaireHT->getValue().toDouble())+", ";
	requete+="unite = \""+unite->getValue()+"\", gereStock = \""+gereStock->getValue()+"\", ";
	requete+="idTva = "+idTva->getValue()+" ";
	requete+=condition;
	
	if(CMySQL::getInstance()->execQuery(requete) != 0) {
		curCode=code->text();
		prixUnitaireHT->setValue(QString("%1").arg(prixUnitaireHT->getValue().toDouble(), 0, 'f', 2));
		setActionCur(CGlobal::acNone);
	}
}
//------------------------------------------------------------------------------
void CArticleFrm::on_actAnnuler_triggered(void) {
	
	QMessageBox msgBox(	QMessageBox::Question, tr("Confirmation"), 
						tr("Etes vous sûre de vouloir annuler ?"), QMessageBox::Yes | QMessageBox::No);
	msgBox.exec();
	
	if(msgBox.result() == QMessageBox::Yes) {
		if(!chargeDonnees(curCode, CGlobal::seNone)) {
			if(!chargeDonnees(curCode, CGlobal::sePrecedent)) {
				if(!chargeDonnees(curCode, CGlobal::seSuivant)) {
					setActionCur(CGlobal::acTableVide);
					return;
				}
			}
		}
	}
}
//------------------------------------------------------------------------------
void CArticleFrm::on_actSupprimer_triggered(void) {
	QMessageBox msgBox(	QMessageBox::Question, tr("Confirmation"), 
						tr("Etes vous sûre de vouloir supprimer la fiche courante ?"), 
						QMessageBox::Yes | QMessageBox::No);
	msgBox.exec();
	
	if(msgBox.result() == QMessageBox::Yes) {
		if(!CMySQL::getInstance()->canDelete("ligneDevis", "article", curCode))
			return;
		if(!CMySQL::getInstance()->canDelete("ligneCommandes", "article", curCode))
			return;
		if(!CMySQL::getInstance()->canDelete("ligneBLs", "article", curCode))
			return;
		if(!CMySQL::getInstance()->canDelete("ligneFactures", "article", curCode))
			return;
		if(!CMySQL::getInstance()->canDelete("prixArticleClient", "article", curCode))
			return;
		
		
		QString requete="DELETE FROM "+masterTable+" WHERE "+primaryKey+"=\""+curCode+"\"";
		
		CMySQL::getInstance()->execQuery(requete);
		
		if(!chargeDonnees(curCode, CGlobal::sePrecedent)) {
			if(!chargeDonnees(curCode, CGlobal::seSuivant)) {
				setActionCur(CGlobal::acTableVide);
			}
		}
	}
}
//------------------------------------------------------------------------------
void CArticleFrm::onChange(void) {
	if(getActionCur() == CGlobal::acNone) {
		setActionCur(CGlobal::acModif);
	}
}
//------------------------------------------------------------------------------
void CArticleFrm::on_actRechercheUneFiche_triggered(void) {
	CFindFrm *findFrm=new CFindFrm(masterTable, this);
	
	findFrm->setModal(true);
	findFrm->exec();
	if(findFrm->result() == QDialog::Accepted) {
		chargeDonnees(findFrm->getResult(), CGlobal::seNone);
	}
}
//------------------------------------------------------------------------------
void CArticleFrm::on_actEntreesSorties_triggered(void) {
	CEntreesSortiesDeStockFrm *entreesSortiesDeStockFrm=new CEntreesSortiesDeStockFrm(curCode, stock->getValue().toDouble(), this);
	
	entreesSortiesDeStockFrm->exec();
	
	if(entreesSortiesDeStockFrm->result() == QDialog::Accepted) {
		chargeDonnees(curCode, CGlobal::seNone);
	}
	
	delete entreesSortiesDeStockFrm;
}
//------------------------------------------------------------------------------
void CArticleFrm::onCombo(CMyComboBox *comboBox) {
	CComboResultFrm *comboResultFrm=new CComboResultFrm(comboBox->getTableRemp(), comboBox->getChampRemp(), this);
	
	comboResultFrm->setModal(true);
	comboResultFrm->exec();
	
	if(comboResultFrm->result() == QDialog::Accepted) {
		comboBox->setValue(comboResultFrm->getResult());
	}
	
	delete comboResultFrm;
}
//------------------------------------------------------------------------------
void CArticleFrm::onInvokeHelp(CChamp *champ) {
	CHelp::getInstance()->startHelp("setSource qthelp://alpes-ressources.com.coMexpert-"+VERSION_LOGICIEL+"/doc/article.html#"+champ->getTable()+"."+champ->getChamp());
}
//------------------------------------------------------------------------------
void CArticleFrm::filterVentes(QString filtre) {
	ventesWidget->clearTable();
	loadGrilleVentes(filtre);
}
//------------------------------------------------------------------------------
void CArticleFrm::onChangeTva(void) {
	onChange();
	
	if(actionCur != CGlobal::acAffiche) {
		QSqlQuery *query;
		
		tvaNom->setValue("");
		if(CMySQL::getInstance()->execQuery("SELECT nom FROM tva WHERE id=\""+idTva->getValue()+"\"", &query) != 0) {
			query->next();
			tvaNom->setValue(query->record().value("nom").toString());
		}
		
		delete query;
	}
}
//------------------------------------------------------------------------------
